<?php


namespace App\Services;
use App\Models\MemberLegal;
use App\Models\Order;
use App\Models\OrderRemark;

/**
 *
 * 天创法诉查询
 */
class YpcreditService
{

    public static $connectTimeout = 30;//30 second
    public static $readTimeout = 80;//80 second

    const HOST='http://api.ypcredit.com/litigation/getPersonLitigationV2';
    const HOSTAssessment='http://api.tcredit.com/assessment/jk70036';
    const APPID='d9c98e73f55f4a248a76569665a1a2dc';
    const tokenID='2237b2de3d7d4381a6fe9fae6dcaf68a';

    public static function query($post=[],$order_id=0)
    {
        $array=[];
        $array['authId']=1;
        $array['isCpt']=1;
        $array['name']=$post['cert_name'];
        $array['idcard']=$post['cert_no'];
        $array['mobile']=$post['mobile'];
        $uid=$post['id']??0;
        $res=MemberLegal::query($post['cert_no']);
        if($res){
            self::addLog('天创法诉查询',$array,$res);

            if(!$res['is_legal']&&$order_id){
                Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                $add_remark = [
                    'uid'=>'23',
                    'username'=>'法诉',
                    'create_time'=>time(),
                    'remark'=>'机构查询出用户法诉',
                    'order_id'=>$order_id
                ];
                OrderRemark::insert($add_remark);
            }
          return $res;
        }else{
            $signature=self::getTokenKey(self::HOST,self::tokenID,$array);
            $array['appId']=self::APPID;
            $array['tokenKey']=$signature;
            $res=http_post(self::HOST,$array);
            self::addLog('天创法诉查询',$array,$res);
            $result=json_decode($res,true);
            if(!isset($result['status'])||$result['status']!=0){
                return false;
            }
            if($result['status']==0&&$result['data']['result']==0&&$result['data']['detail']){
                //&&isset($result['data']['detail']['zxgg'][0])&&$result['data']['detail']['zxgg'][0]['pname']==$post['cert_name']
                if($order_id){
                    Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                    $add_remark = [
                        'uid'=>'23',
                        'username'=>'法诉',
                        'create_time'=>time(),
                        'remark'=>'机构查询出用户法诉',
                        'order_id'=>$order_id
                    ];
                    OrderRemark::insert($add_remark);
                }
                    MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,0,$res);
            }else{
                MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,1,$res);
            }
        }
    }

    public static function queryAssessment($post=[],$order_id=0)
    {
        $array=[];
        $array['name']=$post['cert_name'];
        $array['idcard']=$post['cert_no'];
        $array['mobile']=$post['mobile'];
        $uid=$post['id']??0;
        $res=MemberLegal::query($post['cert_no']);
        if($res){
            self::addLog('天创法诉查询',$array,$res);

            if(!$res['is_legal']&&$order_id){
                Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                $add_remark = [
                    'uid'=>'23',
                    'username'=>'法诉',
                    'create_time'=>time(),
                    'remark'=>'机构查询出用户法诉',
                    'order_id'=>$order_id
                ];
                OrderRemark::insert($add_remark);
            }
            return $res;
        }else{

            $param = self::aes_encrypt(json_encode($array,JSON_UNESCAPED_UNICODE), str_replace('-', '', self::tokenID));
            $params=['param'=>$param];
            $signature=self::getTokenKey(self::HOSTAssessment,self::tokenID,$params);

            $params['appId']=self::APPID;
            $params['tokenKey']=$signature;
            $res=http_post(self::HOSTAssessment,$params);
            $params=array_merge($params,$array);

            $result=json_decode($res,true);
            $result['data_decrypt'] = self::aes_decrypt($result['data'], self::tokenID);
            self::addLog('天创黑名单查询',$params,$result);

            if(!isset($result['status'])||$result['status']!=0){
                return false;
            }
            $data = self::aes_decrypt($result['data'], self::tokenID);

            if($result['status']==0&&$data['black_level']){
                //&&isset($result['data']['detail']['zxgg'][0])&&$result['data']['detail']['zxgg'][0]['pname']==$post['cert_name']
                if($order_id){
                    Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                    $add_remark = [
                        'uid'=>'23',
                        'username'=>'机构',
                        'create_time'=>time(),
                        'remark'=>'机构查询出用户黑名单',
                        'order_id'=>$order_id
                    ];
                    OrderRemark::insert($add_remark);
                }
                MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,0,$res);
            }
        }

    }

    private static function aes_encrypt($input, $key) {
        $method = 'AES-128-ECB';

        $key = hex2bin($key);

        $result = openssl_encrypt($input, $method, $key, 1);
        return bin2hex($result);
    }

    private static function aes_decrypt($input, $key) {
        $method = 'AES-128-ECB';

        $key = hex2bin($key);

        $result = openssl_decrypt(hex2bin($input),$method,$key,1);
        return $result;
    }
    public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }

    private static function getTokenKey($url, $tokenId, $params){
        ksort($params);
        $str = '';
        foreach ($params as $key => $value) {
            if (!empty($value)) {
                $str = $str.$key.'='.$value.',';
            }
        }
        if (strlen($str) > 0) {
            $str = substr($str, 0, strlen($str) - 1);
        }
        $tokenKey = md5($url.$tokenId.$str);
        return $tokenKey;
    }
    /*
*排序并格式化参数方法，签名时需要使用
*/
    protected  static function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . ",";
        }
        $reqPar='';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }



}
